import {
  md5,
  cookie,
  Loading
} from 'vux'
var CryptoJS = require("crypto-js")
import Vue from 'vue'
import axios from 'axios'
import Qs from 'qs' //qs一般装了axios就自带不用再装，如果没有，自己安装下
import moment from 'moment' //导入文件
import JSEncrypt from 'jsencrypt'
import _ from 'lodash'
import store from '@/store'
let instance = axios.create({
  baseURL: '', //这里配置你自己的url
  transformRequest: [function (data) {
    data = Qs.stringify(data) //序列化参数
    return data
  }],
  withCredentials: true // 允许携带cookie
})
let pending = []; //声明一个数组用于存储每个ajax请求的取消函数和ajax标识

let cancelToken = axios.CancelToken;

let removePending = (config) => {
  for (let p in pending) {
    if (config.remove) { //当当前请求在数组中存在时执行函数体
      pending[p].f(); //执行取消操作
      pending.splice(p, 1); //把这条记录从数组中移除
    }
  }
}
//添加请求拦截器
instance.interceptors.request.use(config => {
  if (checkNetWork()) {
    Vue.$vux.loading.show({
      text: "Loading"
    })
    setTimeout(() => {
      Vue.$vux.loading.hide();
    }, 30000)
  } else {
    //执行离线状态时的任务
    Vue.$vux.loading.hide();
  }
  let url = config.url;
  // console.log('config',config);
  //IS_GET_TOKEN统一控制是否需要带上token值，isStringInclude()方法是自定义判断字段中是否含有数组中字段的方法       打包时使用store.state.IS_GET_TOKEN&&  开发时用true|| 
  if (store.state.IS_GET_TOKEN&& !isStringInclude(url, ['LoginServlet', 'getToken', 'auth'])) {
    let urlArr = url.split('?');
    let extParams = urlArr[1]; //取出原有带在url的参数作为getReqUrl方法的extParams参数  
    if (config.params) { //可能url上的参数在parmas里也需要取出来并且将params置为{}  
      let arr = Object.keys(config.params);
      if (arr && arr.length) {
        let paramsArr = arr.map(key => {
          return `${key}=${config.params[key]}`;
        });
        extParams = `${extParams}&${paramsArr.join('&')}`;
        config.params = {};
      }
    }
    config.url = getReqUrl(urlArr[0], extParams);
    config.url = encodeURI(config.url);
    // console.log('config.url', config.url);`
  }

  removePending(config); //在一个ajax发送前执行一下取消操作
  config.cancelToken = new cancelToken((c) => {
    //这里的ajax标识我是用请求地址&请求方式拼接的字符串，当然你可以选择其他的一些方式
    if (config.remove) {
      pending.push({
        u: config.url + '&' + config.method,
        f: c
      });
    }
  });
  return config;
}, error => {
  Vue.$vux.loading.hide();
  return Promise.reject(error);
});
//添加响应拦截器
instance.interceptors.response.use(res => {
  // setTimeout(()=>{

  // },3000)
  removePending(res.config); //在一个ajax响应后再执行一下取消操作，把已经完成的请求从pending中移除
  Vue.$vux.loading.hide();
  //登出 if(res.data&&(res.data.UserNotLogin == 1||(res.data.FixError&&res.data.FixError.includes('FIX-20012')))){
  //    router.push('/')
  //    Vue.$vux.toast.text('登录超时，请重新登录','middle')
  // }
  return res;
}, error => {
  return {
    data: {
      errmsg: error.message
    }
  };
});
export default instance;

export const isStringInclude = (str, arr) => {
  return str.search(eval(`/${arr.join('|')}/`)) !== -1;
}

//按服务器拼接获取task详细信息请求的参数
export const getTaskParams = (obj) => {
  let configs = JSON.parse(obj.DATACONFIGS);
  let workItemId = obj.TASKID; //obj.WrkID;
  let keyid = obj.BIZKEY; //obj.KeyID;
  let defKey = obj.DEFKEY; //obj.defKey;
  let FlowID = obj.INSTID; //obj.FlowID;
  let nodeId = obj.NODEID; //obj.nodeId;
  // let defId = obj.defId;

  let formId = configs.formId; //表单id
  let bizObjId = configs.bizObjId; //业务对象
  let formId_Detail = configs.detailObjIds; //明细表业务对象
  let vDetail = "";
  if (formId_Detail == "") {
    vDetail = "";
  } else {
    vDetail = ',"' + formId_Detail.replace(/,/g, "\",\"") + '"  ';
  }
  return '{"_method": "formService.getFormData",  ' +
    '"requestEventData": {' +
    '    "eventType": "formInitEvent", ' +
    '    "formType": 1,  ' +
    '    "bizObjId": "' + bizObjId + '",  ' +
    '    "formId": "' + formId + '"  ' +
    '},' +
    '"useType": "modify",  ' +
    '"getData": {' +
    '    "useType": "modify",  ' +
    '    "objName": "' + bizObjId + '",  ' +
    '    "relatedObj": [' +
    '        "' + bizObjId + '"  ' +
    vDetail +
    '    ],' +
    '    "pk": [' +
    '        {' +
    '            "key": "GUID",  ' +
    '            "value": "' + keyid + '" ' //任务待办的KeyID  b
    +
    '        }' +
    '    ]' +
    '},' +
    '"getToolbar": {' +
    '    "useType": "modify",  ' +
    '    "objName": "' + bizObjId + '", ' +
    '    "viewId": "' + formId + '",  ' +
    '    "defId": "' + encodeURIComponent(keyid) + '", ' //任务待办的defId
    +
    '    "defKey": "' + defKey + '", ' //任务待办的defKey   
    +
    '    "instId": "' + FlowID + '", ' //任务待办的FlowID   
    +
    '    "taskId": "' + workItemId + '", ' //任务待办的WrkID  
    +
    '    "nodeId": "' + nodeId + '" ' //任务待办的nodeId
    +
    '}' + '}'
}

export const getUserDetailParams = (user) => {
  return '{"_method": "formService.getFormData",' +
    '"requestEventData": {' +
    '"eventType": "formInitEvent",' +
    '"formType": 1,' +
    '"bizObjId": "PER_BASE_SELF",' +
    '"formId": "UserInfo"' +
    '},' +
    '"useType": "view",' +
    '"getData": {' +
    '"useType": "view",' +
    '"objName": "PER_BASE_SELF",' +
    '"relatedObj": ["PER_BASE_SELF"],' +
    '"pk":[]' +
    '},' +
    '}'
}

export const getRiskParams = (obj, taskListIng) => {
  let configs = JSON.parse(obj.DATACONFIGS);
  let keyid = obj.GUID; //obj.KeyID;

  let formId = configs.formId; //表单id
  let bizObjId = configs.bizObjId; //业务对象
  let formId_Detail = configs.detailObjIds; //明细表业务对象
  let vDetail = "";
  if (formId_Detail == "") {
    vDetail = "";
  } else {
    vDetail = ',"' + formId_Detail.replace(/,/g, "\",\"") + '"  ';
  }
  return '{"_method": "formService.getFormData",  ' +
    '"requestEventData": {' +
    '    "eventType": "formInitEvent", ' +
    '    "formType": 1,  ' +
    '    "bizObjId": "' + bizObjId + '",  ' +
    '    "formId": "' + formId + '"  ' +
    '},' +
    '"useType": "modify",  ' +
    '"getData": {' +
    '    "useType": "modify",  ' +
    '    "objName": "' + bizObjId + '",  ' +
    '    "relatedObj": [' +
    '        "' + bizObjId + '"  ' +
    vDetail +
    '    ],' +
    '    "pk": [' +
    '        {' +
    '            "key": "GUID",  ' +
    '            "value": "' + keyid + '" ' //任务待办的KeyID  b
    +
    '        }' +
    '    ]' +
    '},' +
    '"getSysVar": {' +
    '"now":"{sysDate.Now}",' +
    '"test_2":"{sysLoginUser.username}",' +
    '"INPUTERNAME": "{sysLoginUser.loginId}",  ' +
    '"PHONENUM": "{sysLoginUser.tel}",  ' +
    '"INPUTERDEPTNAME": "{sysLoginUser.orgName}",' +
    '"INPUTERDEPTPATHID": "{sysLoginUser.orgPathId}",' +
    '"text_0": "{sysDate.Today}",' +
    '},' +
    '"getFormVerify": {' +
    '    "objName": "' + bizObjId + '", ' +
    '    "viewId": "' + formId + '",  ' +
    '},' +
    '"getToolbar": {' +
    '    "useType": "modify",  ' +
    '    "objName": "' + bizObjId + '", ' +
    '    "viewId": "' + formId + '",  ' +
    '    "defKey": "' + bizObjId + '",  ' +
    '    "defId": "' + keyid + '",  ' +
    '    "instId": "' + taskListIng[0].instId + '",  ' +
    '    "taskId": "' + taskListIng[0].taskId + '",  ' +
    '    "nodeId": "' + taskListIng[0].nodeId + '",  ' +
    '}' + '}'
}

export const pattern = function (fmt) {
  if (!!fmt) {
    fmt = fmt.replace('yyyy', 'YYYY').replace('dd', 'DD').replace('hh', 'HH')
  } else {
    fmt = 'YYYY-MM-DD HH:mm'
  }
  return moment(this).format(fmt)
}


//重新组织请求url，原始url中不能含参数
//加上token、timestamp、salt、sign
//sign=MD5(token+timestamp+salt+其他参数)
//ExtParams 必须是 a=1&b=2 形式的字符串
export const getReqUrl = (url, ExtParams) => {
  let token = window.localStorage.getItem("token") || "";
  let salt = "EcidiMOASalt";
  var Params = "";
  var timestamp = (new Date()).valueOf();
  Params += "timestamp=" + timestamp + "&token=" + token;
  if (typeof (ExtParams) != "undefined" && ExtParams != "")
    Params = Params + "&" + ExtParams;
  var ParamArr = sortUrlParams(Params);
  ParamArr = objKeySort(ParamArr);
  var paramstr = [];
  for (var i in ParamArr) {
    paramstr.push(i + "=" + ParamArr[i]);
  }
  paramstr = paramstr.join("&");
  var sign = md5(paramstr + "&salt=" + salt);
  //console.log(paramstr);
  if (url.includes('?')) {
    return url + "&" + paramstr + "&sign=" + sign;
  } else {
    return url + "?" + paramstr + "&sign=" + sign;
  }

}
//获取url里的参数，return object
function sortUrlParams(str) {
  if (typeof str !== 'string') {
    return {};
  }
  var paramObj = {};
  var paramArr = decodeURI(str).split('&');
  for (var i = 0; i < paramArr.length; i++) {
    //temp 将第一个等号转换为# 防止参数中出现多个等号时请求出错
    // var temp = paramArr[i].replace(/=/,"#");
    var tmp = paramArr[i].split('=');
    var key = tmp[0];
    var value = tmp[1] || "";
    //if (typeof value === 'string' && isNaN(Number(value)) === false && value !== "") {
    //  value = Number(value);
    //}
    if (typeof paramObj[key] === 'undefined') {
      paramObj[key] = value;
    } else {
      var newValue = Array.isArray(paramObj[key]) ? paramObj[key] : [
        paramObj[key]
      ];
      newValue.push(value);
      paramObj[key] = newValue;
    }
  }
  return paramObj;
}
//Object排序
function objKeySort(obj) {
  var newkey = Object.keys(obj).sort();
  var newObj = {};
  for (var i = 0; i < newkey.length; i++) {
    newObj[newkey[i]] = obj[newkey[i]];
  }
  return newObj;
}

// //按服务器拼接参数
// export const getTaskParams = (item)=>{
//   if(item.WEBNAME){
//       switch(item.WEBNAME){
//         case "purchasesubsys":return "_objName=PUR_PLAN&_defKey=Pur_Plan&_defId=Pur_Plan%25253A1%25253Aac43a8c0-3450-47d3-b7c7-751fcbe4c896&_instId=16e2d05c-f88b-4fe8-9d4b-f82744e0aa6a&_taskId=09ad2e34-f776-4780-8b7f-2fbb177fb052&_nodeId=UserTask_4&_nodeName=%252525E9%252525A1%252525B9%252525E7%2525259B%252525AE%252525E7%252525BB%2525258F%252525E7%25252590%25252586%252525E5%252525AE%252525A1%252525E6%2525259F%252525A5&_agent=&_pk=GUID&_pkValue=1523584846063100218919&_useType=modify&sysform=1"
//       }
//   }else{
//     return "";
//   }
// }



//生成guid
export const guid = () => {
  return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
    let r = Math.random() * 16 | 0,
      v = c == 'x' ? r : (r & 0x3 | 0x8);
    return v.toString(16);
  });
}

//判断平台
export const judgeDeviceType = () => {
  var ua = window.navigator.userAgent.toLocaleLowerCase();
  var isIOS = /iphone|ipad|ipod/.test(ua);
  var isAndroid = /android/.test(ua);
  return {
    isIOS: isIOS,
    isAndroid: isAndroid
  };
}
//判断网络状态
export const checkNetWork = () => {
  let networkState = navigator.connection.type;
  console.log("网络状态", networkState);
  if (networkState == 'none') {
    return false;
  } else {
    return true;
  }
}

//数组转换成树
export const toTree = (data, _this) => {

  // 删除 所有 children,以防止多次调用
  data.forEach(function (item) {
    delete item.children;
    if ((item.PARENTID === '2832' || item.ORG_PATHID.split('.').length === 7) && item.NAME !== '绍兴市轨道交通集团有限公司') { // leaf node
      item.leaff = true
    }
  });

  // 将数据存储为 以 id 为 KEY 的 map 索引数据列
  let map = {};
  data.forEach(function (item) {
    map[item.ID] = item;
  });
  // console.log(map);

  let val = [];
  data.forEach(function (item) {
    // 以当前遍历项，的pid,去map对象中找到索引的id
    let parent = map[item.PARENTID];

    // 好绕啊，如果找到索引，那么说明此项不在顶级当中,那么需要把此项添加到，他对应的父级中
    if (parent) {
      (parent.children || (parent.children = [])).push(item);
    } else {
      //如果没有在map中找到对应的索引ID,那么直接把 当前的item添加到 val结果集中，作为顶级
      val.push(item);
    }
  });
  data.forEach((item) => {
    // if(this.type == 'person'){
    if (!item.children) {
      // getPersonByDept(item, _this)
    }
    // }else{
    //   item.leaf = true
    // }
  })
  return val;
}
export const toTreeWithSearch = (dataa, value, _this) => {
  let data = _.cloneDeep(dataa)
  let leafNode = [];
  let rootNode = {};
  data.forEach(function (item, i) {
    // ensure current item is leaf node and it hasn't the value user want to search
    delete item.children
    if ((item.PARENTID === '2832' || item.ORG_PATHID.split('.').length === 7) && item.NAME !== '绍兴市轨道交通集团有限公司') { // leaf node
      item.leaff = true
      if (item.NAME.indexOf(value) !== -1) {
        leafNode.push(item)
      }
    }
  })
  if (leafNode.length === 0) {
    return []
  }
  // 将数据存储为 以 id 为 KEY 的 map 索引数据列
  let map = {};
  data.forEach(function (item) {
    map[item.ID] = item;
  });
  let pList1 = []; // maintain a parent list
  leafNode.forEach(function (item, i) {
    let parent = map[item.PARENTID]
    if (parent) { // there must be a if judge,or it will be say children is undefined
      (parent.children || (parent.children = [])).push(item)
      if (parent.NAME === '绍兴市轨道交通集团有限公司') {
        let parent1 = map[parent.PARENTID]
        if (parent1) {
          parent.open = true;
          parent1.open = true;
          (parent1.children || (parent1.children = [])).push(parent)
          pList1.push(parent1)
          return
        }
      }
      parent.open = true;
      pList1.push(parent);
    }
  })
  pList1.forEach(function (item) {
    let parent = map[item.PARENTID]
    parent.open = true;
    (parent.children || (parent.children = [])).push(item)
    if (!rootNode.ID) {
      parent.open = true;
      rootNode = parent;
    }
  })
  return [rootNode];
}
//获取人员并放入部门下
function getPersonByDept(item, _this) {
  if (item.children) {
    return false;
  }
  _this.getPerson(item.ID, '', (res) => {
    if (res.data.data) {
      let personList = res.data.data
      personList.forEach((item) => {
        item.leaf = true
      })
      _this.$set(item, 'children', personList)
    }
  })
}

export const downloadFile = (url, name) => {
  // window.requestFileSystem(LocalFileSystem.PERSISTENT, 0,  (fs)=> {

  // console.log('打开的文件系统: ' + fs.name);
  // fs.root.getFile(this.fileName, { create: true, exclusive: false },
  // (fileEntry)=> {
  let fileUrl = cordova.file.dataDirectory + name
  let fileTransfer = new FileTransfer();
  fileTransfer.download(
    url, fileUrl, (entry) => {
      entry.file(data => {
        console.log(data)
        cordova.plugins.fileOpener2.open(fileUrl, data.type, {
          error: function (e) {
            console.log('Error status: ' + e + ' - Error message: ' + e);
          },
          success: function () {
            console.log('open successfully');
          }
        }); // showOpenWithDialog使用手机上安装的程序打开下载的文件
      });
      console.log("download complete: " + entry.toURL());
    },
    (error) => {
      console.log("download error source " + error.source);
      console.log("download error target " + error.target);
      console.log("download error code" + error.code);
    },

    false, {}
  )
  // }, ()=>{})}, ()=>{});
}

export const signMD5 = (json) => {
  var appkey = "020f6e877d0328cfa3f454bf925231d5"
  var secret = "196d91eaa08463ccd1846f3371e1dc3e"
  var signstr = ""
  var newjson = {}
  newjson = json
  newjson._app_key = appkey
  var date = new Date()
  var year = date.getFullYear()
  var month = buquan(date.getMonth() + 1, 2)
  var day = buquan(date.getDate(), 2)
  var hou = buquan(date.getHours(), 2)
  var min = buquan(date.getMinutes(), 2)
  var sec = buquan(date.getSeconds(), 2)
  var timestamp = year + "-" + month + "-" + day + " " + hou + ":" + min + ":" + sec;
  newjson._timestamp = timestamp
  var parmaNameArr = [];
  var parmaStrArr = [];
  for (name in newjson) {
    parmaNameArr.push(name)
  }

  parmaNameArr.sort(function (a, b) {
    return a > b ? 1 : -1
  });
  signstr += secret;

  for (var i = 0; i < parmaNameArr.length; i++) {
    var key = parmaNameArr[i];
    if (typeof (value) == "object") {
      var value = JSON.stringify(newjson[key]);
      signstr += key + value;
    } else {
      var value = newjson[key];

      signstr += key + value;
    }
  }
  signstr += secret;
  var sign = md5(signstr);
  newjson._sign = sign;

  //公匙加密AES密匙
  var encrypt = new JSEncrypt();
  encrypt.setPublicKey(cookie.get("pubkey"));
  var AESKey = cookie.get("AESKey");
  //encrypt.setPublicKey($.cookie("pubkey"));
  //var AESKey=$.cookie("AESKey");
  // if($.cookie("AESEncryption")==true||$.cookie("AESEncryption")=="true"){
  if (cookie.get("AESEncryption") === true || cookie.get("AESEncryption") === "true") {
    for (key in newjson) {
      if (key != "_AESKey") {
        newjson[key] = AESencrypt(newjson[key]);
      }
    }
    newjson._AESKey = encrypt.encrypt(AESKey);
  }
  return newjson
}

function buquan(num, length) {

  var numstr = num.toString();
  var l = numstr.length;
  if (numstr.length >= length) {
    return numstr
  }
  for (var i = 0; i < length - l; i++) {
    numstr = "0" + numstr
  }
  return numstr
}

function AESencrypt(word) {
  var key = CryptoJS.enc.Utf8.parse(cookie.get("AESKey"));
  var srcs = CryptoJS.enc.Utf8.parse(word);
  var encrypted = CryptoJS.AES.encrypt(srcs, key, {
    mode: CryptoJS.mode.ECB,
    padding: CryptoJS.pad.Pkcs7
  });
  return encrypted.toString();
}

function AESdecrypt(word) {
  var key = CryptoJS.enc.Utf8.parse(cookie.get("AESKey"));
  var decrypt = CryptoJS.AES.decrypt(word, key, {
    mode: CryptoJS.mode.ECB,
    padding: CryptoJS.pad.Pkcs7
  });
  return CryptoJS.enc.Utf8.stringify(decrypt).toString();
}



var x_PI = 3.14159265358979324 * 3000.0 / 180.0;
var PI = 3.1415926535897932384626;
var a = 6378245.0;
var ee = 0.00669342162296594323;

/**
 * 百度坐标系 (BD-09) 与 火星坐标系 (GCJ-02)的转换
 * 即 百度 转 谷歌、高德
 * @param bd_lon
 * @param bd_lat
 * @returns {*[]}
 */
function bd09togcj02(bd_lon, bd_lat) {
  var x_pi = 3.14159265358979324 * 3000.0 / 180.0;
  var x = bd_lon - 0.0065;
  var y = bd_lat - 0.006;
  var z = Math.sqrt(x * x + y * y) - 0.00002 * Math.sin(y * x_pi);
  var theta = Math.atan2(y, x) - 0.000003 * Math.cos(x * x_pi);
  var gg_lng = z * Math.cos(theta);
  var gg_lat = z * Math.sin(theta);
  return [gg_lng, gg_lat]
}

/**
 * 火星坐标系 (GCJ-02) 与百度坐标系 (BD-09) 的转换
 * 即谷歌、高德 转 百度
 * @param lng
 * @param lat
 * @returns {*[]}
 */
function gcj02tobd09(lng, lat) {
  var z = Math.sqrt(lng * lng + lat * lat) + 0.00002 * Math.sin(lat * x_PI);
  var theta = Math.atan2(lat, lng) + 0.000003 * Math.cos(lng * x_PI);
  var bd_lng = z * Math.cos(theta) + 0.0065;
  var bd_lat = z * Math.sin(theta) + 0.006;
  return [bd_lng, bd_lat]
}

/**
 * WGS84转GCj02
 * @param lng
 * @param lat
 * @returns {*[]}
 */
export function wgs84togcj02(lng, lat) {
  var lat = +lat
  var lng = +lng
  if (out_of_china(lng, lat)) {
    return [lng, lat]
  } else {
    var dlat = transformlat(lng - 105.0, lat - 35.0)
    var dlng = transformlng(lng - 105.0, lat - 35.0)
    var radlat = (lat / 180.0) * PI
    var magic = Math.sin(radlat)
    magic = 1 - ee * magic * magic
    var sqrtmagic = Math.sqrt(magic)
    dlat = (dlat * 180.0) / (((a * (1 - ee)) / (magic * sqrtmagic)) * PI)
    dlng = (dlng * 180.0) / ((a / sqrtmagic) * Math.cos(radlat) * PI)
    var mglat = lat + dlat
    var mglng = lng + dlng
    return [mglng, mglat]
  }
}

/**
 * GCJ02 转换为 WGS84
 * @param lng
 * @param lat
 * @returns {*[]}
 */
function gcj02towgs84(lng, lat) {
  if (out_of_china(lng, lat)) {
    return [lng, lat]
  } else {
    var dlat = transformlat(lng - 105.0, lat - 35.0);
    var dlng = transformlng(lng - 105.0, lat - 35.0);
    var radlat = lat / 180.0 * PI;
    var magic = Math.sin(radlat);
    magic = 1 - ee * magic * magic;
    var sqrtmagic = Math.sqrt(magic);
    dlat = (dlat * 180.0) / ((a * (1 - ee)) / (magic * sqrtmagic) * PI);
    dlng = (dlng * 180.0) / (a / sqrtmagic * Math.cos(radlat) * PI);
    mglat = lat + dlat;
    mglng = lng + dlng;
    return [lng * 2 - mglng, lat * 2 - mglat]
  }
}

function transformlat(lng, lat) {
  var ret = -100.0 + 2.0 * lng + 3.0 * lat + 0.2 * lat * lat + 0.1 * lng * lat + 0.2 * Math.sqrt(Math.abs(lng));
  ret += (20.0 * Math.sin(6.0 * lng * PI) + 20.0 * Math.sin(2.0 * lng * PI)) * 2.0 / 3.0;
  ret += (20.0 * Math.sin(lat * PI) + 40.0 * Math.sin(lat / 3.0 * PI)) * 2.0 / 3.0;
  ret += (160.0 * Math.sin(lat / 12.0 * PI) + 320 * Math.sin(lat * PI / 30.0)) * 2.0 / 3.0;
  return ret
}

function transformlng(lng, lat) {
  var ret = 300.0 + lng + 2.0 * lat + 0.1 * lng * lng + 0.1 * lng * lat + 0.1 * Math.sqrt(Math.abs(lng));
  ret += (20.0 * Math.sin(6.0 * lng * PI) + 20.0 * Math.sin(2.0 * lng * PI)) * 2.0 / 3.0;
  ret += (20.0 * Math.sin(lng * PI) + 40.0 * Math.sin(lng / 3.0 * PI)) * 2.0 / 3.0;
  ret += (150.0 * Math.sin(lng / 12.0 * PI) + 300.0 * Math.sin(lng / 30.0 * PI)) * 2.0 / 3.0;
  return ret
}

/**
 * 判断是否在国内，不在国内则不做偏移
 * @param lng
 * @param lat
 * @returns {boolean}
 */
function out_of_china(lng, lat) {
  return (lng < 72.004 || lng > 137.8347) || ((lat < 0.8293 || lat > 55.8271) || false);
}
/**
 * WGS84 转换为 BD09坐标
 *
 * */
export const wgs84tobd09 = (lng, lat) => {
  var list = wgs84togcj02(lng, lat)
  return gcj02tobd09(list[0], list[1])
}

export const gc02tobd09 = (lng, lat) => {
  return gcj02tobd09(lng, lat)
}
